import Vue from 'vue';

import Router from 'vue-router';


import AuthRoutes from '@/router/fullPath';

import store from '@/store';

import { hasPermission, getToken } from '@/libs/appHead';


Vue.use(Router);

const router =  new Router({
  mode:'history',
  linkActiveClass:'is-active',
  scrollBehavior(to,from,savePosition){ // 点击浏览器的前进后退或切换导航触发
    if(savePosition){
      return savePosition;
    }else{
      return {x:0,y:0}
    }

  },
  routes:AuthRoutes

});
var Auth = {};
//全局路由守卫
router.beforeEach((to,from,next)=>{
  let _token = getToken();
  if(_token && _token.length){  // 判断token是否存在
    if(to.path == '/login'){
      router.replace({
        path:'/'
      });
    }else{

      // 页面跳转前先判断用户角色是否存在
      if(!store.getters.roleName){
        store.dispatch('GetUserInfo').then(res=>{
          Auth = {
            terminalType:res.terminalType,
            roleName:res.roleName
          };
          store.dispatch('getClassType').then(list=>{
            store.dispatch('getWechatAndAlipay').then(
              (data)=>{
                if(data && !data.result){
                  router.replace({
                    path:'/set-account'
                  });
                }else{
                  next(to.fullPath);
                }
              }
            ).catch(err => this.$message.error(err));
          });
        }).catch(()=>{});

      }else{
        //拿到用户信息与班课类型后，每次进入页面时再次和用户信息与终端设备进行匹配
        if(to.meta && to.meta.roleName && to.meta.roleName.length && to.meta.terminalType && to.meta.terminalType.length){
          //需要权限验证
          if(hasPermission(to,Auth)){
            next();
          }else{
            next('/'); //没有权限，直接进入首页
          }
        }else{
          //不需要权限验证
          next();
        }
      }


    }

  }else{
    if(to.path == '/login'){
      store.commit('clearLoginStatus',()=>{
        next();
      });
    }else{
      store.commit('clearLoginStatus',()=>{
        next('/login');
      });
    }
  }
});

export default router;

